<?php
/**
 * Created by PHPStorm
 * User: xieshentao
 * Date: 2021/3/31
 * Email: <939369942@qq.com>
 */
namespace basic\services;
use basic\exceptions\AuthException;
use Firebase\JWT\JWT;
use think\facade\Config;

class JwtTokenService
{

    /**
     * Notes:
     * @param int $id
     * @param string $type
     * @param $exp
     * @param array $params
     * @return array
     * @Author: xiest
     * @Date: 2021/3/31 14:03
     */
    public function createToken(int $id,string $type,$exp,array $params = []): array
    {
        $time = time();
        $host = app('request')->host();
        $params += [
            'iss' => $host,
            'aud' => $host,
            'iat' => $time,
            'nbf' => $time,
            'exp' => $exp,
        ];
        $params['jti'] = [$id, $type];
        $token = JWT::encode($params, Config::get('app.app_key', 'default'));
        $params['token'] = $token;
        $params['out'] = $exp * 60 * 60;
        return $params;
    }


    /**
     * Notes:
     * @param string $token
     * @return object
     * @Author: xiest
     * @Date: 2021/3/31 14:04
     */
    public function parseToken(string $token)
    {
        return JWT::decode($token,Config::get('app.app_key','default'),['HS256']);
    }

    public function decode(string $token)
    {
        $tks = explode('.', $token);
        if (count($tks) != 3)
            throw new AuthException('Invalid token');

        if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($tks[1])))
            throw new AuthException('Invalid token');

        return $payload;
    }
}